<?php

/**
 * overridden term page
 * @param $term
 * @return array|void
 */
function _board_feed_taxonomy_term_page($term) {
  switch($term->vocabulary_machine_name) {
    case 'board':
      drupal_add_css(drupal_get_path('module', 'board_feed') . '/css/term-board.css');
      return _board_feed_taxonomy_boards($term);
      break;
  }

  module_load_include('inc', 'taxonomy', 'taxonomy.pages');
  return taxonomy_term_page($term);
}


/**
 * board pages
 * @param $term
 */
function _board_feed_taxonomy_boards($term) {
  global $user;

  $board_owner_uid = private_taxonomy_term_get_user($term->tid);
  if(CommonHelper::is_private_board($term) && ($user->uid !== $board_owner_uid)) {
    drupal_access_denied();
    drupal_exit();
  }

  $nids = taxonomy_select_nodes($term->tid, TRUE, variable_get('default_nodes_main', 10));

  $build['#board_feed'] = array(
    'cover' => board_feed_get_cover($term, 'cover_board_feed'),
  );

  $build = array_merge($build, _board_feed_listing($nids));
  return $build;
}

/**
 * overridden /node page (home page)
 */
function _board_feed_node_page() {
  drupal_set_title('');

  $select = db_select('node', 'n')
    ->fields('n', array('nid', 'sticky', 'created'))
    ->condition('n.status', 1)
    ->condition('n.type', NIP_TYPE)
    ->orderBy('n.sticky', 'DESC')
    ->orderBy('n.created', 'DESC')
    ->extend('PagerDefault')
    ->limit(variable_get('default_nodes_main', 10))
    ->addTag('node_access');

  $nids = $select->execute()->fetchCol();

  return _board_feed_listing($nids);
}

/**
 * crabii listing helper
 */
function _board_feed_listing($nids) {
  if(!empty($nids)) {
    // loading libraries
    LibraryHelper::load(array(
      array('name' => 'salvattore',
        'options' => array('scope' => 'footer'),
      ),
      array('name' => 'jquery.autogrow-textarea'),
      array('name' => 'jquery-timeago'),
    ));

    $board_feed = drupal_get_path('module', 'board_feed');
    drupal_add_js($board_feed . '/js/board.js');
    drupal_add_css($board_feed . '/css/board.css');

    $nodes = node_load_multiple($nids);

    $build['nodes-grid'] = array(
      '#type' => 'container',
      '#attributes' => array(
        'class' => array('nodes-grid', 'clearfix', 'row'),
        'data-columns' => '',
      ),
      'nodes' => node_view_multiple($nodes),
    );

    $build['pager'] = array(
      '#theme' => 'pager',
      '#weight' => 5,
    );
  }
  else {
    $build['no_content'] = array(
      '#prefix' => '<p>',
      '#markup' => t('There is currently no content classified with this.'),
      '#suffix' => '</p>',
    );
  }

  return $build;
}
